﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace _List转DataTable
{
    public class PyMethon<T> where T : class
    {
        public static DataTable ListToTable(List<T> Ts)
        {
            DataTable dt = new DataTable();

            PropertyInfo[] parm = typeof(T).GetProperties();

            ///添加表头
            foreach (PropertyInfo p in parm)
            {
                dt.Columns.Add(p.Name, p.PropertyType);
            }
            ///添加值

            foreach (T t in Ts)
            {
                DataRow dr = dt.NewRow();
                foreach (PropertyInfo item in parm)
                {
                    dr[item.Name] = item.GetValue(t, null);
                }
                dt.Rows.Add(dr);
            }
            return dt;
        }
    }
}
